<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>文件共享服务</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/index.css}"></link>
<script type="text/javascript" th:src="@{/js/jquery-3.7.1.min.js}"></script>
<style type="text/css">
.upload {
	border: 1px solid gray;
	padding: 5px;
	margin: 5px 0px;
	width: 600px;
	max-width: 100%;
}
.progress {
	border: 1px solid #ccc;
	border-radius: 10px;
	height: 10px;
	overflow: hidden;
}
.progress > div {
    width: 0px;     
    height: 100%;
    background-color: yellowgreen;
    transition: all .3s ease;
}

.table-wrapper {
	max-width: 100%;
	overflow: auto;
}
table {
	line-height: 1.5em;
}
table td {
	min-width: 5px;
}
table .name {
	min-width: 10em;
}
table .file-type {
	min-width: 3em;
}
table .last-modify {
	min-width: 10em;
}
input {
	margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="app-container">
	<h3 th:text="${path}">/</h3>
	<div th:if="${upload}" class="upload">
		<input type="file" id="file" multiple />
		<button onclick="uploadFile()">上 传</button>
		<div class="progress">
			<div></div>
		</div>
	</div>
	<div><a th:if="${parent}" th:href="'/file/home?path=' + ${parent}">返回上级</a></div>
	<div class="table-wrapper">
		<table>
			<thead>
				<tr>
					<th class="name">名称</th>
					<th class="file-type">类型</th>
					<th>大小</th>
					<th class="last-modify">上次修改</th>
				</tr>
			</thead>
			<tbody>
				<tr th:each="file:${list}">
					<td nowrap="nowrap">			
						<a th:unless="${file.isDir}" th:text="${file.name}" th:href="'/file/download/' + ${file.path}"></a>
						<a th:if="${file.isDir}" th:text="${file.name}" th:href="'/file/home?path=' + ${file.path}"></a>
					</td>
					<td>
						<span th:text="${file.isDir ? '目录' : '文件'}"></span>
					</td>
					<td>
						<span th:text="${file.humanSize}"></span>
					</td>
					<td>
						<span th:text="${file.humanLastModify}"></span>
					</td>
				</tr>
			</tbody>
		</table>
	</div>
</div>
<script>
function uploadFile() {
	const files = document.getElementById("file").files;
	const formData = new FormData();
	for (let i=0; i < files.length; i++) {
		console.log(files[i].name);
		formData.append("file", files[i]);
	}
	$.ajax({
		url: "/file/upload",
		type: "POST",
		data: formData,
		contentType: false,
		processData: false,
		xhr: progressRequest,
		success: data => {
			if (data.success) {
				alert("上传成功");
			} else {
				alert("上传失败-->" + data.errmsg);
			}
		},
		error: () => {
			alert("上传失败");
		}
	});
}
function progressRequest() {
	const xhr = new XMLHttpRequest();
	xhr.upload.addEventListener('progress', event => {
		const rate = (event.loaded / event.total) * 100 + '%';
		$('.progress > div').css('width', rate);
	});
	return xhr;
}
</script>
</body>
</html>